# ======================================================================
#
# Copyright (C) ADN
# ADN::LIBRARY::PING::Ping Ping.pm
# Description:
#  - Gestion des PING ICMP
#  - Gestion of the IMCP PING
#
# ======================================================================

package ADN::LIBRARY::PING::Ping;

use POE;
use POE::Component::Client::Ping;
use ADN::CONF::Read;

# #######################
# CREATION OF THE SELF OBJECT + INIT. VARIABLES
# #######################
sub new
{
	# Construction de l'objet $self
	my $self = shift;
	my $class = ref($self) || $self;
	return $self if ref $self;
	$self = bless {} => $class;
	my $conf = ADN::CONF::Read->new();
  	if ( $conf =~ m/^[-]1$/smx ) {
    	return -1;
  	}
  	my %PING = $conf->PING();
  	$self->{TIMEOUT} = $PING{timeout};
  	@{$self->{ADDRESSE}} = ();
  	undef $conf;
  	return ($self);
}

# #######################
# FUNCTION MULTI-PING
# #######################
sub start
{
    my $self = shift;
    @{$self->{ADDRESSE}} = @_;
    @{$self->{RESULT}} = ();

    POE::Component::Client::Ping->spawn( Alias => 'pinger',
					                     					 Timeout => $self->{TIMEOUT});

    POE::Session->create(inline_states =>
										{
			     							_start => sub {
              								foreach my $address (@{$self->{ADDRESSE}}) {
		             							$_[KERNEL]->post(pinger => ping => pong => $address);
              								}
           								},
			     							pong => sub {
             											my ($request_address, $request_timeout, $request_time1) = @{$_[ARG0]};
             											my ($response_address, $roundtrip_time, $request_time2) = @{$_[ARG1]};
             											if (defined $response_address) {
		            										push @{$self->{RESULT}}, $request_address;
             											}
           											},
			 							});
	$poe_kernel->run();
  return $self->duplicate_ip();
}

# #######################
# DELETE DUPLICATE IP
# #######################
sub duplicate_ip
{
   my $self = shift;
   my $str = '';

   foreach my $host (@{$self->{RESULT}})
   {
		 if ($str !~ m/$host/smx)
		 {
				$str .= $host.',';
		 }
	 }
	 @{$self->{RESULT}} = split /,/smx, $str;
	 return @{$self->{RESULT}};
}

# #######################
# DESTROY OBJECT
# #######################
sub DESTROY {
    my $self = shift;
    return;
}
1;
__END__
